//
//  BTTopicDetailVC.m
//  BaxTer
//
//  Created by wsj2015 on 16/9/7.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "BTTopicDetailVC.h"
#import "BTTopicDetailHeader.h"
#import "UITableView+MTTHeaderFooterFittingHeight.h"
#import "BTContentCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "BTLabelCell.h"
#import "BTTopicDetailModel.h"
#import "BTCourseDetailVC.h"

@interface BTTopicDetailVC ()


@property (nonatomic,  strong) UIView *header;

@property (nonatomic,  assign) NSInteger currentSelectIndex;

@property (nonatomic,  strong) UIView *sectionView;

@property (nonatomic,  strong) BTTopicDetailModel *topicDetail;


@property (nonatomic,  strong) UIView *navView;


@end

@implementation BTTopicDetailVC
{
    CGFloat  _halfHeight;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    _halfHeight = 150;
}
- (void)configUI{

    self.title = @"专题详情";
    self.currentSelectIndex = 0;
   BTTopicDetailHeader *header = [BTTopicDetailHeader detailheader];
    weakSelf_define;
    header.priseBlock = ^(UIButton *sender){
        
        BOOL isLike = !sender.selected;
        [weakSelf priseAndCollectRequest:isLike :-1 withBtn:sender];
       
    };
    header.collectBlock = ^(UIButton *sender){
        
        BOOL iscollected = !sender.selected;
        [weakSelf priseAndCollectRequest:-1 :iscollected withBtn:sender];
        
    };
   
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = header;
     [self.tableView mtt_updateTableHeaderViewHeightWithAnimated:NO];
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"BTContentCell" bundle:nil] forCellReuseIdentifier:@"BTContentCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BTLabelCell" bundle:nil] forCellReuseIdentifier:@"BTLabelCell"];
  
    
    //自定义返回按钮
    [self.view addSubview:self.navView];
    UIView *view = [UIView new];
    view.frame = CGRectMake(8, 24, 39, 39);
    view.layer.masksToBounds =YES;
    view.tag = 100;
    view.backgroundColor = [UIColor colorWithWhite:.3 alpha:.4];
    view.layer.cornerRadius = 39/2;
    [self.view addSubview:view];
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame  = view.bounds;
    btn.tag = 101;
    [btn setImage:[UIImage imageNamed:@"back copy"] forState:UIControlStateNormal];

    [btn addTarget:self action:@selector(pageBack) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
  
    [self requestTopicDetail];

    
    
//    self.tableView.contentSize = CGSizeMake(kScreenWidth, kScreenHeight -44);

}
- (UIView *)navView{
    if (!_navView) {
        _navView = [UIView new];
        _navView.frame = CGRectMake(0, 0, kScreenWidth, 64);
        _navView.backgroundColor = [UIColor whiteColor];
        _navView.alpha = 0;
        
        
        UILabel *label =[UILabel new];
  
        label.frame = CGRectMake(80, 20+12, kScreenWidth - 160, 20);
        label.text  =@"专题详情";
        label.textColor = [UIColor blackColor];
       
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont boldSystemFontOfSize:17];
        [_navView addSubview:label];
        
        UIView *line =[UIView new];
        line.frame = CGRectMake(0, 64 -kOnePX, kScreenWidth, kOnePX);
        line.backgroundColor = kBorderColor;
        [_navView addSubview:line];
       
        
    }
    return _navView;
}
- (void)pageBack{
   

    [self.navigationController setNavigationBarHidden:NO animated:YES];
 
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)requestTopicDetail{
   
    UIView *view = [self.view viewWithTag:100];

    if (!self.topicDetail) {
        [self wsj_showLodingGif];
        
    }
    [self.view  bringSubviewToFront:view];
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    //wsjtest
    params[@"id"] = @(self.topicId);
    params[@"userId"] = @(1);
    defineWeakSelf;
     [[BTNetworkManager sharedMg] POST:kTopicDetail parameters:params success:^(NSDictionary * responseObject) {
         
         
         if (responseObject_success) {
             //这里关于训练营的 一次请求
             if (weakSelf.traingCampDict && [weakSelf.traingCampDict[@"finished"] boolValue] == NO &&[weakSelf.topicDetail.topicStatus integerValue] == 1) {
                 
                 [weakSelf postServerCampstepFinishedWithID:[weakSelf.traingCampDict[@"id"] integerValue]];
             }
             
             
             weakSelf.topicDetail = [BTTopicDetailModel mj_objectWithKeyValues:responseObject[@"data"]];
             [weakSelf.tableView reloadData];
         }
         
         [weakSelf.tableView mtt_updateTableHeaderViewHeightWithConfig:^(BTTopicDetailHeader * view) {
             view.model = weakSelf.topicDetail;
             
         } animated:YES];
         [weakSelf wsj_hideLodingGif];
//         [weakSelf.tableView.header endRefreshing];
        
     } failure:^(NSString *err) {
         [weakSelf wsj_hideLodingGif];
//         [weakSelf.tableView.header endRefreshing];
         [weakSelf pageBack];
     }];
    

}
- (void)postServerCampstepFinishedWithID:(NSInteger)campStepId{
    
    weakSelf_define;
    NSString *url =[NSString stringWithFormat:@"%@/%@",kPostCourseHasFinished,@(campStepId)];
    [[BTNetworkManager sharedMg] GET:url parameters:nil success:^(id responseObject) {
        if (responseObject_success) {
            if ([weakSelf.topicDetail.topicStatus integerValue] == 1) {
                weakSelf.traingCampDict[@"finished"] = @(YES);
            }
            
        }
    } failure:^(NSString *err) {
        
    }];
    
    
}

#pragma mark - 点赞和收藏

//  传-1 (不操作)  1 (yes)  0 (NO)
- (void)priseAndCollectRequest:(NSInteger)isLike :(NSInteger)isCollected withBtn:(UIButton *)btn{
    
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    
    
    
    //wsjtest
    params[@"topicID"] = @(self.topicId);
//    params[@"userID"]  =@(1);
    if (isLike != -1) {
        params[@"islike"]  =@(isLike);

    }
    if (isCollected != -1) {
        params[@"iscollect"]  =@(isCollected);
        
    }
    cwqHud;
    weakSelf_define;
    [[BTNetworkManager sharedMg] POST:kPriseAndCollect parameters:params success:^(NSDictionary * responseObject) {
        [hud hide:YES];
        if (responseObject_success) {
            btn.selected = !btn.selected;
            UIControlState state = btn.isSelected?UIControlStateSelected:UIControlStateNormal;
            if (isLike != -1) {
               
                NSInteger likeCount = [weakSelf.topicDetail.topiclikecount integerValue];
                if (isLike) {
                    likeCount ++;
                }else{
                    likeCount --;
                }
                weakSelf.topicDetail.topiclikecount = [NSString stringWithFormat:@"%@",@(likeCount)];
                [btn setTitle: [NSString stringWithFormat:@"%@",@(likeCount)] forState:state];

            }else{
                NSInteger collecteCount = [weakSelf.topicDetail.topiccollectcount integerValue];
                if (isCollected) {
                    collecteCount ++;
                }else{
                    collecteCount --;
                }
                weakSelf.topicDetail.topiccollectcount = [NSString stringWithFormat:@"%@",@(collecteCount)];
                [btn setTitle: [NSString stringWithFormat:@"%@",@(collecteCount)] forState:state];

            
            
            }
                   }
//        cwqAlertMessage(responseObject[@"data"]);
    } failure:^(NSString *err) {
        [hud hide:YES];
    }];
    

}


-(void)viewWillAppear:(BOOL)animated{
   
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  
    if (self.currentSelectIndex == 0) {
        return 1;
    }
    return self.topicDetail.baxterTopicdetails.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (self.currentSelectIndex ==0) {
        BTLabelCell *cell =[tableView dequeueReusableCellWithIdentifier:@"BTLabelCell" forIndexPath:indexPath];
         cell.contentL.htmlText = self.topicDetail.topicdesc;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        return cell;
    }
   BTCourseInTopicDetial *model = self.topicDetail.baxterTopicdetails[indexPath.row];
   BTContentCell *cell  =[tableView dequeueReusableCellWithIdentifier:@"BTContentCell" forIndexPath:indexPath];
    cell.model = model;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
     tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.currentSelectIndex == 0) {
        [self.tableView registerNib:[UINib nibWithNibName:@"BTLabelCell" bundle:nil] forCellReuseIdentifier:@"BTLabelCell"];
        weakSelf_define;
        CGFloat h =[tableView fd_heightForCellWithIdentifier:@"BTLabelCell" configuration:^(BTLabelCell * cell) {
            cell.contentL.text = weakSelf.topicDetail.topicdesc;;
        }];
        CGFloat cy = kScreenHeight - 64 - 44 -h ;
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, cy, 0);
        return h + 10;
    }
    
    return 49;
    
}
- (UIView *)sectionView{
    if (!_sectionView) {
        _sectionView =[UIView new];
        _sectionView.frame  =CGRectMake(0, 0, kScreenWidth, 44);
        _sectionView.backgroundColor = [UIColor whiteColor];
        
        NSArray *titleArr = @[@"详情",@"目录"];
        CGFloat w = kScreenWidth /2;
        for (int i = 0; i<2; i++) {
            UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
            [btn addTarget:self action:@selector(changeContent:) forControlEvents:UIControlEventTouchUpInside];
            [btn setTitle:titleArr[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn setTitleColor:kMainColor forState:UIControlStateSelected];
            btn.titleLabel.font = [UIFont systemFontOfSize:15];
            [_sectionView addSubview:btn];
            btn.frame = CGRectMake( w * i, 0, w, 42);
            btn.tag = 300 +i;
            if (i == 0 ) {
                btn.selected = YES;
            }
        }
        
        UIView *line =[UIView new];
        line.frame = CGRectMake(0, 42, kScreenWidth, 2);
        line.backgroundColor = kMainColor;
        [_sectionView addSubview:line];
        UIView *moveView =[UIView new];
        moveView.tag = 800;
        moveView.frame = CGRectMake(0, 40, kScreenWidth /2, 4);
        moveView.backgroundColor = kMainColor;
        [_sectionView addSubview:moveView];

    }
    return _sectionView;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    return self.sectionView;

}




- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.currentSelectIndex ==1) {
    
        BTCourseInTopicDetial *model =self.topicDetail.baxterTopicdetails[indexPath.row];
        BTCourseDetailVC *vc =[BTCourseDetailVC new];
        vc.courseId = [model.course_id integerValue];
        [self.navigationController pushViewController:vc animated:YES];
        
    }
   
}


- (void)changeContent:(UIButton *)btn{
    
    if (btn.tag - 300 == self.currentSelectIndex) {
        return;
    }
    
    UIButton *lastBtn = [self.sectionView viewWithTag:self.currentSelectIndex + 300];
    lastBtn.selected = NO;
    self.currentSelectIndex = btn.tag - 300;
    btn.selected = !btn.selected;
     UIView *moveView =[self.sectionView viewWithTag:800];
    CGRect frame = moveView.frame;
    
    
 
    if (self.currentSelectIndex ==0) {
        frame.origin.x = 0;
       
     
    }else{
        frame.origin.x = kScreenWidth /2;
        
       
    }
    
    [UIView animateWithDuration:.35f delay:0 usingSpringWithDamping:.7 initialSpringVelocity:.6 options:UIViewAnimationOptionAllowAnimatedContent animations:^{
        moveView.frame = frame;
    } completion:^(BOOL finished) {
       
       
    }];
    [UIView performWithoutAnimation:^{
        [self.tableView reloadSections: [NSIndexSet indexSetWithIndex:0] withRowAnimation:0];
    }];
    
   
//    [self.tableView reloadRowsAtIndexPaths:indexArr withRowAnimation:0];
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
   
        CGFloat offsetY = scrollView.contentOffset.y;
        CGFloat  alp;
         if (offsetY >=  100) {
             alp = 1.0;
           
             self.navView.alpha = 1;
        } else if(offsetY>0 && offsetY < 100) {
            alp = offsetY /100;
            self.navView.alpha = alp;
        }else{
            self.navView.alpha = 0;
        }
    
    
}


@end
